
import { ccs } from "../../util/services";
import { game } from "../control/game";
import { companyBase, figureBase, ItemBase } from "../control/Item/ItemBase";
import { actionType, assetsType, companyType, diseaseType, edu, foodModel, giftType, itemType, playerType, randomEventType, relationObject, schoolType, studyModel, workType } from "../gameType";
import figureModel from "./figureModel";
import heroBase from "./heroBase";
import skillModel from "./skill";

//人物基础类
export class playerClass extends heroBase {

    
    constructor(player?: playerType) {
        super(player, true);
    }
    eat(food: foodModel) {
        let timer = game.timerMgr;
        this.changeEffect(food.effect, 1);
        timer.addTime(food.time, this);
    }
    addRank() {
        this.heroInfo.rank.star ++;
        if(this.heroInfo.rank.star > 3) {
            this.heroInfo.rank.star = 1;
            this.heroInfo.rank.id ++;
            if(this.heroInfo.rank.id > ccs.dataMgr.getRankList().length - 1) {
                this.heroInfo.rank.id = ccs.dataMgr.getRankList().length - 1;
            }
        }
    }
    reduceRank() {
        this.heroInfo.rank.star --;
        if(this.heroInfo.rank.star <= 0) {
            this.heroInfo.rank.star = 3;
            this.heroInfo.rank.id --;
            if(this.heroInfo.rank.id <= 0) {
                this.heroInfo.rank.id = 1;
                this.heroInfo.rank.star = 0;
            }
        }
    }
    goSchool(data: schoolType) {
        //上学
        if(game.timerMgr.gameTime.month > 4) {
            return ccs.winMgr.showWin("toast", { msg: "今年报名结束了哦，请明年再来"});
        }
        if(data.score > this.heroInfo.eduScore) {
            return ccs.winMgr.showWin("toast", {msg: "分数不够"});
        }
        if(data.power > this.heroInfo.power) {
            return ccs.winMgr.showWin("toast", {msg: "精力不足"});
        }
        if(data.price > this.getFamilyMoney()) {
            ccs.winMgr.closeWin("popAlert");
            ccs.winMgr.showWin("popAlert", { content: "是否自费上学？", cb: () => {
                if(data.price > this.heroInfo.money) {
                   ccs.winMgr.showWin("toast", {msg: "金钱不足，可以通过父母获得"});
                   return ;
                } else {
                    let res = this.calMoney(-data.price);
                    if(!res) return;
                    let year = 0;
                    if(this.heroInfo.school) {
                        year = this.heroInfo.school.leftYear;
                    }else {
                        year = data.year;
                    }
                    this.heroInfo.school = data;
                    this.heroInfo.school.leftYear = year;
                    game.recordMgr.addList({name: "你", action: "开始上学了，", effect: "每个月少了" + data.power + "点精力"});
                    game.recordMgr.addList({name: "你", action: "开始上学了"})
                }
                ccs.mainEmitter.emit("updateSchool");
            }});
        } else {
            this.familyPay(data.price);
            let year = 0;
            if(this.heroInfo.school) {
                year = this.heroInfo.school.leftYear;
            }else {
                year = data.year;
            }
            this.heroInfo.school = data;
            this.heroInfo.school.leftYear = year;
            ccs.winMgr.showWin("toast", {msg: "开始上学了"});
            game.recordMgr.addList({name: this.heroInfo.name, action: `父母交了学费`, effect: `家庭资产- ${this.heroInfo.school.price}`});
            game.recordMgr.addList({name: "你", action: "开始上学了，", effect: "每个月少了" + data.power + "点精力"})
            ccs.mainEmitter.emit("updateSchool");
        }
        if(data.type == "xiaoxue") {
            game.playerMgr.achieveFinish("xiaoxue", 1);
        }
        if(data.price >= 100000){
            game.playerMgr.achieveFinish("guizuxueyuan", 1);
        }
    }
   
    //生成父母
    randomParent() {
        let hero = new figureModel("father");
        hero.randomInfo(28, {sex: ccs.gf.getSexStr("b")});
        this.bag.figureBag.addItem(new figureBase(hero.figureInfo));
        let monther = new figureModel("monther");
        monther.randomInfo(24, {sex: ccs.gf.getSexStr("g")});
        this.bag.figureBag.addItem(new figureBase(monther.figureInfo));
        for(let i = 0; i<2;i++ ) {
            let lover = new figureModel("friend");
        lover.randomInfo(13, {sex: ccs.gf.getSexStr("g")});
        this.bag.figureBag.addItem(new figureBase(lover.figureInfo));
        }
        
        //设定关系
        this.heroInfo.relation.father = hero.figureInfo;
        this.heroInfo.relation.monther = monther.figureInfo
        this.heroInfo.name = this.randomMyName();
    }
    addAge() {
        this.addYear(); 
        this.calSchool();
        this.getLineEvent();
        this.bag.figureBag.addAge(); //人物关系
        this.heroInfo.payYear = 0;
        this.heroInfo.incomeYear = 0;
        //计算学费
        ccs.mainEmitter.emit("updateAge");//刷新属性
        ccs.mainEmitter.emit("updateInfo");//刷新属性
        ccs.mainEmitter.emit("updateSchool"); //刷新学校列表
    }
    
    
    //更新资产信息
    updateAssets() {
        let arr: assetsType[] = this.bag.assetsBag.bag.items;
        arr.forEach(val => {
            if(val.month > 0) {
                val.month --;
                val.leftMoney -= val.monthPay;  
                 game.recordMgr.addList({action: `偿还${val.name}${val.monthPay}的贷款和利息，`, effect: `钱 -${val.monthPay}，剩余月数 ${val.month}` });
                if(val.month == 0) {
                    //结束
                    this.heroInfo.assetsPayMonth -= val.monthPay * (1 + val.interest);
                    game.recordMgr.addList({action: `${val.name}的贷款已还完`});
                }
            }
        })
        ccs.mainEmitter.emit('updateAssets');
    }
    updateCompany() {
        let arr: companyType[] = this.bag.companyBag.bag.items;
        let item: companyBase = null;
        arr.forEach(val => {
            item = this.bag.companyBag.getItem(val.id);
            //库存减去
            item.calRent(); //租金
            //ceo成长
            item.ceoUp();
        })
        ccs.mainEmitter.emit('upCompany');
    }
    //计算孩子的培养费用
    calChildPay() {
        let list = this.bag.figureBag.getRelation("son");
        let money = 0;
        list.forEach(val => {
            if(val.data.hero.age <= 3) {
                money += 2500;
            }
        })
        this.calMoney(-money);
    }
    //计算月支出和年支出
    calPayMonth() {
        if(this.heroInfo.work) {
            this.heroInfo.power -= this.heroInfo.work.power;
        }
        if(!this.heroInfo.house && this.heroInfo.age >= 24) {
          
            // this.calMoney();
        }
        this.heroInfo.money += this.heroInfo.assetsIncomeMonth - this.heroInfo.assetsPayMonth;
        this.heroInfo.payYear  += this.heroInfo.payMonth + this.heroInfo.assetsPayMonth;
        this.heroInfo.incomeYear += this.heroInfo.incomeMonth + this.heroInfo.assetsIncomeMonth;
        //重置
        this.heroInfo.payMonth = 0;
        this.heroInfo.incomeMonth = 0;
    }
    calCardTime() {
        game.cardMgr.reduceTime();
        ccs.mainEmitter.emit('refreshCard');
    }
    calPay(assetsPay: number, assetsIncome: number, monthPay: number, monthIncome: number = 0) {
        this.heroInfo.assetsIncomeMonth += assetsIncome;
        this.heroInfo.assetsPayMonth += assetsPay;
        this.heroInfo.payMonth += monthPay;
        this.heroInfo.incomeMonth += monthIncome;
    }
    reducePower(power: number): boolean {
        if(this.heroInfo.power >= power) {
            this.heroInfo.power -= power;
            ccs.mainEmitter.emit("updateAttribute");
            return true;
        } else {
            ccs.winMgr.showWin("toast", { msg: `精力不够了呢`});
            return false;
        }
    }
    // 父母带你去看病

    //重置体力
    resetPower() {
        this.heroInfo.power = this.heroInfo.maxPower;
        if(this.heroInfo.school) {
            this.heroInfo.power -= this.heroInfo.school.power;
            if(this.heroInfo.power < 0) {
                this.heroInfo.power = 0;
            }
        }
        //增加工作经验值
        if(this.heroInfo.work) {
            this.addExp();
            //增加压力
            this.heroInfo.pressure = ccs.gf.handlerCount(this.heroInfo.pressure, this.heroInfo.work.pressure, 100);
            ccs.mainEmitter.emit("upWorkInfo");

        }
        //没有房子并且大于24岁
        if(!this.heroInfo.house && this.heroInfo.age >= 25) {
            game.recordMgr.addList({action: `支付房租及基础生活费${this.heroInfo.rent}元`})
            this.heroInfo.payMonth += this.heroInfo.rent;
            this.heroInfo.money -= this.heroInfo.rent;
            // this.heroInfo.payMonth += 2500;
        }
        this.getPocketMoney();//获取零花钱
        //生病处理      QWERTYUIO\23        this.diseaseReduceTime();
        
        //每个月扣除家庭花销
        let money = 0, father = this.bag.figureBag.getRelation("father")[0].data.hero,monther = this.bag.figureBag.getRelation("monther")[0].data.hero;
        if(father.work) {
            money += Math.trunc(Math.random() * father.work.income * 0.5);
        }else if( monther.work) {
            money += Math.trunc(Math.random() * monther.work.income * 0.5);
        }
        let pay =  money + 4000;
        //小于三岁，每个月1000元费用
        if(this.heroInfo.age <= 3) {
            pay += 2000;
        }
        if(this.heroInfo.age <= 25) {
            this.familyPay(pay);
            if(this.heroInfo.disease.length > 0) {
                if(Math.random() >= 0.4) {
                    this.goHospital(this.heroInfo.disease[0], true);
                }
            }
        }
        //如果上大学，每个月多500元
        this.getSchoolMoney();
        
        //升学压力
        this.reduceMonth();
        //证书
        this.calCardTime();
        //随机事件
        let per = Math.random();
        if(per <= 0.35) {
            this.randomEvent(per);
        }
        if(this.heroInfo.house) {
           this.changeEffect(this.heroInfo.house.effect);
        } else if(this.heroInfo.age >= 7){
            this.changeEffect({
                health: -1, 
                pressure: 1,
            })
        }
        if(this.heroInfo.pressure >= 50) {
            game.recordMgr.addList({'action': '压力过大，请注意劳逸结合哦'});
        }
        //减去房租
        ccs.mainEmitter.emit("updateAttribute", {power: this.heroInfo.maxPower});
        this.diseaseReduceTime();
    }
    randomEvent(per) {
        let list = ccs.dataMgr.getHappenRandomEvent(per);
        if(list.length <= 0) return; 
        let event: randomEventType = list[Math.round(Math.random() * (list.length - 1))];
        let can = false;
            //钱财事件
            for(let key in event.condition) {
                if(key == 'school' && this.getSchool() && edu[this.getSchool().id] >= event.condition[key]) {
                    can = true;
                }else {
                    if(this.heroInfo[key] >= event.condition[key]) {
                        can = true;
                    }
                }
            }
            if(event.need && can) {
                if(event.need['power']) {
                    if(this.heroInfo.power <= event.need['power']){ 
                        return ;
                    }
                    // this.changeEffect({power: event.need['power']}, -1);
                }
                if(event.need['money']) {
                    if(event.need["money"] > this.heroInfo.money){
                        return ;
                    }
                }
            }

        if(can) {
            ccs.winMgr.showWin("popAlert", {content: `${event.desc}`, title: event.name, cb: () => {
                let effect = event.effect, result = event.result;
                //如果是社交类事件
                if(event.type == 'social') {
                    let hero = new figureModel("friend");
                    hero.randomInfo(ccs.gf.randomInt(this.heroInfo.age - 5, this.heroInfo.age + 10), {sex: ccs.gf.getSexStr(Math.random() >= 0.5? "b": "g")});
                    this.bag.figureBag.addItem(new figureBase(hero.figureInfo));
                    this.achieveFinish("friend", 1);
                    return ;
                } else if(event.type == "ad") {
                    ccs.AD.showVideoAd(() => {
                        this.changeEffect(effect);
                    })
                    return ;
                }
                if(Math.random() <= 0.6 && !event.isSingle) {
                    //失败
                    effect = event.fail;
                    result = event.lose;
                }
                //产生影响
                this.changeEffect(effect);
                ccs.winMgr.showWin("toast", {msg: `${ccs.gf.getEffectString(effect)}`})
                game.recordMgr.addList({action: `${result}`, effect: `${ccs.gf.getEffectString(effect)}`})
            },cancel: () => {
                game.recordMgr.addList({action: `${event.desc}, 你选择了放弃`});
            },
            ensureText: event.btn[0],
            cancelText: event.btn[1],
            });
            
        }
        
    }
    work(work: workType) {
        let idx = this.heroInfo.works.findIndex(val => val.id == work.id)
        this.heroInfo.work = this.heroInfo.works[idx];
        // this.heroInfo.assetsIncomeMonth += this.heroInfo.work.income;
    }
    goMarray() {
        //结婚
        if(this.heroInfo.relation.wife) {
            return ccs.winMgr.showWin("toast", {msg: "一生只允许一个伴侣噢"});
        }
        this.heroInfo.relation.chat.relation = "couples";
        this.heroInfo.relation.wife = this.heroInfo.relation.chat;
        game.recordMgr.addList({name: "你", action: `与${this.heroInfo.relation.chat.hero.name}喜结连理，步入婚姻的殿堂`, location: "圣索菲亚大教堂"});
    }
    makeChild() {
        let percent = 0.5;
        if(this.heroInfo.age <= 16) {
            percent = 0;
        }else if(this.heroInfo.age >= 50) {
            percent = 0.2;
        }else if((this.heroInfo.age >50 && this.heroInfo.age <= 70)) {
            percent = 0.1;
        }
        if(Math.random() <= percent) {
            ccs.winMgr.showWin("toast", { msg: `恭喜获得孩子`});
            //新建一个人物
            let son = new figureModel("son");
            son.randomInfo(1, this.getDNA());
            this.bag.figureBag.addItem(new figureBase(son.figureInfo));
            this.achieveFinish('child', 1);
            game.recordMgr.addList({name: "你", action: `与${this.heroInfo.relation.chat.hero.name}经常做运动，终于有了孩子`});
        }else {
            ccs.winMgr.showWin("toast", { msg: `该养身子了`});
            game.recordMgr.addList({name: "你", action: `与${this.heroInfo.relation.chat.hero.name}努力想生个孩子`});
        }
    }
    // 获取基因
    getDNA(): Partial<playerType> {
        let DNA = {};
        let percent = 2;
        for(let key in this.heroInfo) {
            if(key == "learn" || key == "iq" || key == "eq" || key == 'maxPower') {
                if(key == "learn" || key == "iq" || key == "eq" ) {
                    percent = 10;
                } else if(key == 'maxPower') {
                    percent = 30;
                }
                DNA[key] = Math.trunc((this.heroInfo[key] + this.heroInfo.relation.wife.hero[key])/percent);
            }
        }
        Object.assign(DNA, {
            sex: ccs.gf.getSexStr(Math.random() >= 0.5? "b": "g"),
            liftTime: 1200,
            charm: 1,
            name: this.randomSonName(),
            age: 1,
            income: 0,
            money:0,
            relation: {
                father: new figureModel("father", this.heroInfo),
                monther: new figureModel("monther", this.heroInfo.relation.wife.hero)
            }
        })
        return DNA;
    }
    randomMyName() {
        let childName = ccs.dataMgr.getRandomFigure().name;
        let index = 1;
        if(childName.length == 2 || childName.length == 3) {
            index = 1;
        } else {
            index = 2;
        }
        
        childName = childName.slice(index);
        let firstName = "陈";
        if(this.heroInfo.relation.father.hero.name.length == 2 || this.heroInfo.relation.father.hero.name.length == 3){
            firstName = this.heroInfo.relation.father.hero.name.slice(0, 1);
        }else {
            firstName = this.heroInfo.relation.father.hero.name.slice(0, 2);
        }
        return firstName + childName;
    }
    randomSonName() {
        let childName = ccs.dataMgr.getRandomFigure().name;
        let index = 1;
        if(childName.length == 2 || childName.length == 3) {
            index = 1;
        } else {
            index = 2;
        }
        
        childName = childName.slice(index);
        let firstName = "陈";
        //父亲的名字
        if(this.heroInfo.name.length == 2 || this.heroInfo.name.length == 3){
            firstName = this.heroInfo.name.slice(0, 1);
        }else {
            firstName = this.heroInfo.name.slice(0, 2);
        }
        childName = firstName + childName;
        return childName;
    }
    love() {
        //交往
        this.heroInfo.relation.chat.relation = "love";
        this.heroInfo.relation.love = this.heroInfo.relation.chat;
        game.recordMgr.addList({name: "你", action: `与${this.heroInfo.relation.chat.hero.name}好感爆棚，你们决定在一起了`});
    }
    
    //获取当前对话的角色
    getCurRole() {
        return this.heroInfo.relation.chat;
    }
    begMoney() {
        if(Math.random() >= 0.5) {
            let money = Math.random() * this.getCurRole().hero.work.income;
            this.heroInfo.money += money;
            ccs.winMgr.showWin("toast", {msg: "成功要到" + money + "元"});
            game.recordMgr.addList({name: "你", action: `向${this.heroInfo.relation.chat.hero.name}要到了钱，`, effect: `金钱加${money}`});
        }else {
            game.recordMgr.addList({name: "你", action: `向${this.heroInfo.relation.chat.hero.name}要零花钱，被臭骂了一顿`});
        }
    }
    
    unLove() {
        //分开
        this.heroInfo.relation.chat.relation = "friend";
        this.heroInfo.relation.love = null;
        game.recordMgr.addList({name: "你", action: `与${this.heroInfo.relation.chat.hero.name}交往后并不是很合得来，你选择了放手`});

    }
    unMarray() {
        //离婚
        this.heroInfo.relation.chat.relation = "friend";
        this.heroInfo.relation.wife = null;
        game.recordMgr.addList({name: "你", action: `与${this.heroInfo.relation.chat.hero.name}婚后经常被家暴，最终还是离婚了`});

    }
    //获取公司的盈利影响
    getCompanyEffect(id) {
        let work = game.playerMgr.heroInfo.works.find(val => val.id == id);
        //专业能力30， 魅力20， 情商和智商20
        let effect = work.level/10* 0.3 + this.heroInfo.charm/100*0.2 + (this.heroInfo.eq + this.heroInfo.iq)/200*0.2;
        return effect;
    }
    //执行行为，不用消耗物品
    doAction(action: actionType) {
        if(action.type == "shop" && action.id == "shenmi") {
            //
            if(!this.calMoney(-action.cost)) {
                return ;
            }
            //如果是神秘药水，随机一个属性;
            let arr = ['money', 'health', 'maxPower', 'pressure', 'iq', 'eq', 'learn', 'charm', 'lifeTime'];
            let attr = arr[Math.floor(Math.random() * (arr.length - 1))];
            //百分70的概率是升级的
            let sort = Math.random() <= 0.7? 1: -1,count = Math.round(Math.random() * 5);
            this.changeEffect({[attr]: count}, sort);
            ccs.winMgr.showWin("toast", {msg: `使用了${action.name}, ${ccs.dataMgr.getAttributeNameById(attr).name}: ${sort * count}`});
            game.recordMgr.addList({action: `使用了${action.name}, ${ccs.dataMgr.getAttributeNameById(attr).name}: ${sort * count}`});
            return ;
        }
        let power = action.power;
        if(this.heroInfo.traffic) {
            power = this.heroInfo.traffic.powerEffect * action.power;
        }
        if(power >  this.heroInfo.power) {
             ccs.winMgr.showWin("toast", { msg: `精力不够了呢`});
            return;
        }
        if(!this.calMoney(-action.cost)) {
            ccs.winMgr.showWin("toast", {msg: "金钱不足，可通过投资获取财富"});
            return ;
        }
        let effect = '', maxCount = 100;
        for(let key in action.effect) {
            effect += (ccs.dataMgr.getAttributeNameById(key).name + action.effect[key]);
        }
        this.changeEffect(action.effect);
        if(power && power > 0 ){
            this.heroInfo.power = ccs.gf.handlerCount(this.heroInfo["power"], -power, this.heroInfo["power"]);
        }
        // this.heroInfo.money -= action.cost;
        // this.heroInfo.payMonth += action.cost;
        if(action.type == "shop") {
            ccs.winMgr.showWin("toast", { msg: `你使用了${action.name}，${effect}`});
        }
        ccs.winMgr.showWin("toast", { msg: `你，可强， ${effect}`});
        if(action.type == "travel") {
            this.achieveFinish("travel", 1);
        }
        game.recordMgr.addList({name: "你", action: `${action.name}`, effect: `金钱-${action.cost}，精力消耗${power}，${effect}`});
        //主界面更新
        ccs.mainEmitter.emit("updateAttribute");
    }
    study(study: studyModel, skill: skillModel) {
        let timer = game.timerMgr;
        //培训
        // timer.addTime(study.costTime * this.heroInfo.traffic.effect + study.studyTime * 60, this);
        skill.learnSkill(this.heroInfo, study);
    }
    
    // moveToLocation(id: number) {
    //     if(this.heroInfo.location.id == id) {
    //         ccs.winMgr.showWin("toast", { msg: `想去哪，你到底？`});
    //         return ;
    //     }
    //     //前往目的地
    //     let target = ccs.dataMgr.getDataById("map", id);
    //     let distance = Math.abs(target.location - this.heroInfo.location.location);
    //     //计算路程
    //     let time = distance * 30 <= 0? 20: distance* 30;
    //     //修改当前地点
    //     this.heroInfo.location = target;
    //     game.timerMgr.addTime(time);
    // }
    useItem(item: ItemBase) {
         //使用消耗品 背包减去
         this.bag.itemsBag.delItem(item.data.id, 1);
        //  let _item: ItemBase = this.bag.itemsBag.getItem(item.data.id);
         for(let effect in item.data.effect) {
            //产生影响
            this.heroInfo[effect] = ccs.gf.handlerCount(this.heroInfo[effect], item.data.effect[effect]);
         }
         ccs.winMgr.showWin('toast', { msg: `使用了${item.data.name}，人也变得不一样了`});
        ccs.mainEmitter.emit("updateAttribute", item.data.effect);
    }
    getLineEvent() {
        //判断几岁该去什么学校
        // ccs.winMgr.showWin('popTestWin', {id: "chuzhong"});
        let event = ccs.dataMgr.getLineEvent(this.heroInfo.age);
        if(!event) return;
        let edu = ccs.dataMgr.getEduById(event.id);
        if(event && !this.heroInfo.school&&(edu.need == "wu" || edu.need == this.heroInfo.edu.id)) {
            game.recordMgr.addList({action: `该上${event.name}了，教育是很有必要的哦`});
            let test = ccs.dataMgr.getCardById(this.heroInfo.edu.id);
            if(test) {
                //弹出考试
                ccs.winMgr.showWin('popTestWin', {id: edu.need});
            } else {
                ccs.winMgr.showWin("popAlert", {title: event.name, content: event.desc});
            }
        }
    }
    //进行朋友互动
    doSocial(id: string | number, gift: giftType, name?: string) {
        if(this.heroInfo.traffic) {
            gift.power = this.heroInfo.traffic.powerEffect * gift.power;
        }
        if(this.heroInfo.money < gift.cost) {
            game.recordMgr.addList({name: "你", action: "想送" + gift.name + "给" + name + "，但太穷了。"});
            ccs.winMgr.showWin("toast", {msg: "钱包有点羞涩"});
            return false; 
        } else if( this.heroInfo.power < gift.power) {
            ccs.winMgr.showWin("toast", {msg: "精力有限"});
            return false;
        }
        let isGive = this.bag.figureBag.require(id, gift);

        this.calMoney(-gift.cost);
        this.heroInfo.power = ccs.gf.handlerCount(this.heroInfo.power, -gift.power, this.heroInfo.maxPower);
        if(isGive) {
            game.recordMgr.addList({name: "你", action: "送了" + gift.name + "给" + name, effect: "花费" + gift.cost + "，消耗" + gift.power + "精力，" + `增加了${gift.effect}好感`});
            ccs.winMgr.showWin("toast", {msg: "啾啾，你们的感情正在升温"});
            ccs.mainEmitter.emit("updateRelation");
            return true;
        }else {
            ccs.winMgr.showWin("toast", {msg: "他白了你一眼,似乎没什么兴趣"});
            game.recordMgr.addList({name: "你", action: "送了" + gift.name + "给" + name + ",似乎没什么兴趣。", effect: "花费" + gift.cost + "，消耗" + gift.power + "精力"});
            return false;
        }
    }
}
